import Vue from "vue";
import { getToken } from "@/utils/storage";
import VueRouter from "vue-router";
import Layout from "@/views/layout.vue";
import Login from "@/views/login.vue"; //登录
import Register from "@/views/register.vue"; //注册
// 二级路由
import home from "@/views/children/home.vue";
import Collect from "@/views/children/collect.vue";
import news from "@/views/children/news.vue";
import My from "@/views/children/My.vue";
//三级路由
import Myfavorites from "@/views/secondary/Myfavorites.vue";
Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    //!主页面
    {
      path: "/", //主
      redirect: "home",
      component: Layout,
      // 二级路由
      children: [
        {
          path: "/home",
          component: home,
        },
        {
          path: "/collect",
          component: Collect,
        },
        {
          path: "/news",
          component: news,
        },
        {
          path: "/My",
          component: My,
        },
      ],
    },
    {
      path: "/layout:id", //主
      component: Layout,
    },
    {
      path: "/login",
      component: Login,
    },
    {
      path: "/register",
      component: Register,
    },
    //!子页面
    {
      path: "/Myfavorites",
      component: Myfavorites,
    },
  ],
});
//全局路由守卫
const whiteList = [
  "/login",
  "/register",
  "/home",
  "/",
  "/collect",
  "/news",
  "/user",
  "/My",
]; // 白名单列表，记录无需权限访问的所有页面

router.beforeEach((to, from, next) => {
  //查看本地是否有token
  const token = getToken();
  // 如果有token，直接放行
  if (token) {
    next();
  } else {
    // 没有token的人, 看看你要去哪
    // (1) 访问的是无需授权的页面（白名单），也是放行
    //     就是判断，访问的地址，是否在白名单数组中存在 includes
    if (whiteList.includes(to.path)) {
      next();
    } else {
      // (2) 否则拦截到登录
      next("/login");
    }
  }
});
export default router;
